package com.temp.utils;

import com.temp.exception.BaseException;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Optional;
import java.util.Random;

public class RandomBigDecimalGenerator {

    // 默认最小值
    private static final BigDecimal DEFAULT_MIN = new BigDecimal("90");
    // 默认最大值
    private static final BigDecimal DEFAULT_MAX = new BigDecimal("98");

    private static final Random random = new Random();

    public static void validateAmount(BigDecimal amount,
                                      Optional<BigDecimal> minAmountOpt,
                                      Optional<BigDecimal> maxAmountOpt) {
        if (minAmountOpt.isPresent()) {
            BigDecimal minAmount = minAmountOpt.get();
            if (amount.compareTo(minAmount) < 0) {
                throw new BaseException("apiMsg.amountMin,".concat(String.valueOf(minAmount)));
            }
        }

        if (maxAmountOpt.isPresent()) {
            BigDecimal maxAmount = maxAmountOpt.get();
            if (amount.compareTo(maxAmount) > 0) {
                throw new BaseException("apiMsg.amountMax,".concat(String.valueOf(maxAmount)));
            }
        }
    }

    public static BigDecimal getRandomBetween(Optional<BigDecimal> minOpt, Optional<BigDecimal> maxOpt) {
        // 使用orElseGet提供默认值
        BigDecimal min = minOpt.orElse(DEFAULT_MIN);
        BigDecimal max = maxOpt.orElse(DEFAULT_MAX);

        // 验证min <= max，如果不符合则交换
        if (min.compareTo(max) > 0) {
            BigDecimal temp = min;
            min = max;
            max = temp;
        }

        // 如果min和max相等，直接返回
        if (min.compareTo(max) == 0) {
            return min;
        }

        // 计算差值
        BigDecimal range = max.subtract(min);

        // 生成随机比例(0.0到1.0之间的随机数)
        BigDecimal randomFactor = BigDecimal.valueOf(random.nextDouble());

        // 计算随机值 = min + (range * randomFactor)
        BigDecimal randomValue = min.add(range.multiply(randomFactor));

        // 设置小数位数和舍入模式
        return randomValue.setScale(0, RoundingMode.HALF_UP);
    }
}
